<?php

$loader->requireOnce('ordo/TicketItem.class.php');
$loader->requireOnce('includes/AjaxRender/TicketRender.class.php');

class C_AutoCorrect extends Controller {	
	var $template_mod;					
	
	function C_AutoCorrect($template_mod = "general") {
		parent::Controller();
		if (Celini::getCurrentController() == 'AutoCorrect') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'patient';
		}
		$this->template_mod = $template_mod;

		$this->view->path = 'autocorrect';
	}
	
	public function actionView() {
		$userId = $this->getUserId();
    	$this->assign("dictionary", ORDataObject::factory('Dictionary')->getAllItems($userId));
    	return $this->view->render("view_dictionary.html");
    }
    
    public function actionAddItemAjax() {
    	$userId = $this->getUserId();
    	$dictionaryItem = Celini::newORDO('Dictionary');
    	$abbreviationText = $_POST['abbreviation'];
    	$replacedText = $_POST['replacedText'];
    	if ($dictionaryItem->getId($userId, $abbreviationText) == 0) {
    		$dictionaryItem->addNewItem($userId, $abbreviationText, $replacedText);	
    		$this->buildAddItemResponse($dictionaryItem);
    	} else {
    		echo 0;
    	}
    }
    
	public function actionDeleteItemAjax() {
    	$dictionaryItem = Celini::newORDO('Dictionary');
    	$dictionaryItem->deleteItem($_GET["dictionary_id"]); 	
    }
    
    public function actionReplaceAjax() {
    	$source = trim(ereg_replace( ' +', ' ', $_POST["source"]));
    	$dictionary = Celini::newORDO('Dictionary');
    	$response = $dictionary->getReplacedText($source, $this->getUserId());
    	echo json_encode($response);

    }
    
    private function buildAddItemResponse($dictionaryItem) {
    	$res = $dictionaryItem->getRealPersistenceInfo();
    	//TODO @Localization
    	$dictionaryItemId = $dictionaryItem->get('dictionary_id');
    	$response = "<tr id='$dictionaryItemId'>
    					<td>{$res->fields['abbreviation']}</td>
    					<td>{$res->fields['replaced_text']}</td>
    					<td style='text-align: center'>
    						<a href='javascript:deleteDictionaryItem($dictionaryItemId)'>
    							<img class='imgBtn' src='../images/remove_small.png' border='0' title='".L10nHelper::_("Delete")."'/>
    						</a>
    					</td>
    				</tr>";
    	echo $response;
    }
    
    private function getUserId() {
    	$me =& Me::getInstance();
    	return $me->get_id();
    }
}
?>